package com.hundun.hddeal.controller;
import com.github.pagehelper.PageInfo;
import com.hundun.hddeal.dao.*;
import com.hundun.hddeal.entity.*;
import com.hundun.hddeal.response.Result;
import com.hundun.hddeal.response.ResultUtil;
import com.hundun.hddeal.service.TokenService;
import com.hundun.hddeal.service.lmpl.AdUserServiceImpl;
import com.hundun.hddeal.service.lmpl.GzhServiceImpl;
import com.hundun.hddeal.service.lmpl.PublishServiceImpl;
import com.hundun.hddeal.util.MD5Util;
import com.hundun.hddeal.util.TokenUtil;
import com.hundun.hddeal.util.TokenUtilT;
import com.hundun.hddeal.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;


/**
 * 广告用户
 * @author 谢
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("ad")
public class AdUserController {

    @Autowired
    AdUserServiceImpl adUserService;
    @Autowired
    TokenService tokenService;
    @Autowired
    GzhServiceImpl gzhService;
    @Autowired
    GzhMapper gzhMapper;
    @Autowired
    AdUserMapper adUserMapper;
    @Autowired
    MtUserMapper mtUserMapper;
    @Autowired
    PublishServiceImpl publishService;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    NextOrderMapper nextOrderMapper;
    @Autowired
    TaskOrderMapper taskOrderMapper;
    @Autowired
    PublishMapper publishMapper;

    /**
     * 登陆
     * @param adUser
     * @return
     */
    @PostMapping("login")
    public Result login(@RequestBody AdUser adUser) {
        return adUserService.selectByAdUserId(adUser);
    }

    /***
     * 短信验证登陆
     */
    @PostMapping("noteLogin")
    public Result noteLogin(@RequestBody AdUserVo adUserVo){
        return adUserService.noteLogin(adUserVo.getAdPhone(),adUserVo.getNote());
    }



    /**
     * 注册
     * @param adUser
     * @return
     */
    @PostMapping("register")
    public Result register(@RequestBody AdUser adUser) {
        return adUserService.register(adUser);
    }


    /**
     * 个人信息初始化参数token
     * @param
     * @return
     */
    @PostMapping("getad")
    public Result<AdUser> getInfo(@RequestBody AdUserVo adUserVo) {
        String adUserId = TokenUtilT.getTokenById(adUserVo.getAdUserToken());
        AdUser adUser = adUserService.findAdUserById(adUserId);
        return ResultUtil.success(adUser);
    }



    /**
     * 个人信息初始化表头token
     * @param request
     * @return
     */
    @PostMapping("adUserInfo1")
    public Result<AdUser> getInfo1(HttpServletRequest request) {
        String token = TokenUtil.getTokenById(request);
        AdUser adUser = adUserService.findAdUserById(token);
        return ResultUtil.success(adUser);
    }


    /**
     * 给单个gzh信息
     * @param gzhVo
     * @return
     */
    @PostMapping("getone")
    public Result <GzhBody> getOne(@RequestBody GzhVo gzhVo){
        String ghId = gzhVo.getGhId();
        return gzhService.selectGzhBody(ghId);
    }


    /**
     * 展示公众号
     * @param page
     * @return
     */
    @PostMapping("gzh")
    public Result<PageInfo<GzhBody>> testAll(@RequestBody RequestPageBean page){
        PageInfo<GzhBody> pageInfo = gzhService.selectAllGzh(page.getPageNum(), page.getPageSize(), page.getTypeNames(),
                page.getGzhAge(), page.getGzhSex(), page.getGzhPrice(), page.getFansType(),
                page.getReadNum(), page.getCityOne(), page.getStatus(),page.getGzhName(),page.getGhId(),page.getGzhType(),page.getSort(),
                page.getScore());
        return ResultUtil.success(pageInfo);
    }


    /**
     * 查询用户金额
     * @param map
     * @return
     */
    @PostMapping("getMoney")
    public Result getMoney(@RequestBody Map<String ,String> map){
            String token=map.get("adUserToken");
            String adUserId = TokenUtilT.getTokenById(token);
            AdUser adUser= adUserService.findAdUserById(adUserId);
            adUser.setAdPwd(null);
            return ResultUtil.success(adUser);
    }


    /**
     * 更新广告方个人信息
     * @param adUserVo
     * @return
     */
    @PostMapping("updateAd")
    public Result updateAdUser(@RequestBody AdUserVo adUserVo){
        String token=adUserVo.getAdUserToken();
        String adUserId = TokenUtilT.getTokenById(token);
        AdUser adUser= adUserService.findAdUserById(adUserId);
        if(adUser!=null){
            if("".equals(adUserVo.getAdPhone())) {
                return ResultUtil.error("请填写手机号码");
            }
            if("".equals(adUserVo.getAdCompany())) {
                return ResultUtil.error("请填写公司名称");
            }
            adUser.setAdId(adUserId);
            adUser.setAdCompany(adUserVo.getAdCompany());
            adUser.setAdName(adUserVo.getAdName());

            AdUser adUser1 = adUserMapper.selectPhone(adUserVo.getAdPhone());
            if(adUser1!=null){
                if(!adUser1.getAdPhone().equals(adUserVo.getAdPhone())){
                    return ResultUtil.error("该手机号码已被注册");
                }
            }
            adUser.setAdPhone(adUserVo.getAdPhone());
            adUser.setAdQq(adUserVo.getAdQq());
            adUser.setAdUrl(adUserVo.getAdUrl());
            adUser.setCompanyDescribe(adUserVo.getCompanyDescribe());
            adUser.setCompanyPlace(adUserVo.getCompanyPlace());
            adUser.setAdWx(adUserVo.getAdWx());
            adUser.setAdEmail(adUserVo.getAdEmail());
            adUser.setPhoneNum(adUserVo.getPhoneNum());
            return adUserService.updateByPrimaryKeySelective(adUser);
        }
        return ResultUtil.error("无token");
    }

    /**
     * 查看公众号的个数
     * @param
     * @return
     */
    @PostMapping("getUserCount")
    public Result getUserCount(){
        try{
            TestVo testVo=new TestVo();
            testVo.setMtCount(gzhMapper.selectCount());
            return  ResultUtil.success(testVo);
        }catch (Exception e){
            return ResultUtil.error();
        }

    }

    /**
     * 重置密码
     * @param map
     * @return
     */
    @PostMapping("resetAdMtPwd")
    public Result resetAdPwd(@RequestBody Map<String ,String> map){
          String type=map.get("type");
          try{
              if("1".equals(type)){
                  adUserMapper.resetAdPwd(MD5Util.getSaltMD5(map.get("newPwd")),map.get("adId"),null);
                  return ResultUtil.success();
              }else {
                  mtUserMapper.resetMtPwd(MD5Util.getSaltMD5(map.get("newPwd")),map.get("mtId"));
                  return ResultUtil.success();
              }
          }catch (Exception e) {
              e.printStackTrace();
              return ResultUtil.error();
          }

    }


    /**
     * 注册时判断是否存在用户
     * @param map
     * @return
     */
    @PostMapping("haveAdUser")
    public Result isHaveUser(@RequestBody Map<String,String> map){
        AdUser adUser = adUserMapper.selectByAdUserId(map.get("adId"));
        if (adUser != null) {
            return ResultUtil.error("已存在");
        }
        return ResultUtil.success();
    }


    /**
     * 评价订单
     * @param publish
     * @return
     */
    @PostMapping("publish")
    public Result publish(@RequestBody Publish publish){
        if(publish.getType()==1){
            List<OrderDetail> orderDetails=orderDetailMapper.getOrderHostId(publish.getOrderId());
            orderDetailMapper.updatePublish(publish.getOrderId(),1);
            //循环填入评价表
            for (OrderDetail orderDetail:orderDetails) {
                publish.setGhId(orderDetail.getGhId());
                publishService.insertSelective(publish);

                double scoreFeedback=0;
                List<Publish> publishes=publishMapper.selectByPrimaryKey(publish.getOrderId(),orderDetail.getGhId());
                //计算评分总分
                for (Publish publish1:publishes) {
                    scoreFeedback+=publish1.getScore();
                }
                Gzh gzh=gzhMapper.selectByGhId(orderDetail.getGhId());
                gzh.setScoreFeedback((int)scoreFeedback/publishes.size());//得出平均数存入公众号
                gzhMapper.updateByPrimaryKeySelective(gzh);
            }
        }else {
            taskOrderMapper.updatePublish(publish.getOrderId(),1);
            nextOrderMapper.updatePublish(publish.getOrderId(),1);
            List<NextOrder> nextOrders=nextOrderMapper.getAll(publish.getOrderId());
            for (NextOrder nextOrder:nextOrders) {
                publish.setGhId(nextOrder.getGhId());
                publishService.insertSelective(publish);

                double scoreFeedback=0;
                List<Publish> publishes=publishMapper.selectByPrimaryKey(publish.getOrderId(),nextOrder.getGhId());
                for (Publish publish1:publishes) {//计算评分总分
                    scoreFeedback+=publish1.getScore();
                }
                Gzh gzh=gzhMapper.selectByGhId(nextOrder.getGhId());
                gzh.setScoreFeedback((int)scoreFeedback/publishes.size());//得出平均数存入公众号
                gzhMapper.updateByPrimaryKeySelective(gzh);

            }
        }
        return ResultUtil.success();
    }

    /**
     * 获取评价
     * @param publish
     * @return
     */
    @PostMapping("getPublish")
    public Result getPublish(@RequestBody Publish publish){
        return publishService.selectByPrimaryKey(publish.getOrderId());
    }







}
